import requests


def check_api_plan(api_key):
    """
    通过API请求检查账户计划和限制
    """
    url = "https://api.glassnode.com/v1/metrics/addresses/count"

    params = {
        'a': 'BTC',
        'i': '24h',
        's': '1609459200',  # 2021-01-01
        'api_key': api_key
    }

    try:
        response = requests.get(url, params=params)

        # 检查响应头中的限制信息
        headers = response.headers
        print("=== API限制信息 ===")
        print(f"请求限制: {headers.get('x-ratelimit-limit', 'N/A')}")
        print(f"剩余请求次数: {headers.get('x-ratelimit-remaining', 'N/A')}")
        print(f"重置时间: {headers.get('x-ratelimit-reset', 'N/A')}")

        # 通过可用数据频率推断计划类型
        return analyze_plan_from_headers(headers)

    except Exception as e:
        print(f"查询失败: {e}")
        return None


def analyze_plan_from_headers(headers):
    """从响应头分析计划类型"""
    limit = headers.get('x-ratelimit-limit')
    if limit:
        limit = int(limit)
        if limit <= 100:
            return "Free/Starter Plan"
        elif limit <= 1000:
            return "Advanced Plan"
        else:
            return "Professional/Enterprise Plan"
    return "Unknown"


def get_data_frequencies(api_key):
    """
    测试API Key支持的数据频率
    """
    frequencies = ['1h', '10m', '1m']
    supported_freqs = []

    url = "https://api.glassnode.com/v1/metrics/market/price_usd_close"

    for freq in frequencies:
        params = {
            'a': 'BTC',
            'i': freq,
            's': '1640995200',  # 最近的时间戳
            'api_key': api_key
        }

        response = requests.get(url, params=params)

        if response.status_code == 200:
            data = response.json()
            if data and len(data) > 0:
                supported_freqs.append(freq)
                print(f"✅ 支持 {freq} 频率数据")
            else:
                print(f"❌ 不支持 {freq} 频率数据")
        else:
            print(f"❌ {freq} 频率请求失败: {response.status_code}")
    print(supported_freqs)
    # 根据支持的频率判断计划类型
    return determine_plan_from_frequencies(supported_freqs)


def determine_plan_from_frequencies(frequencies):
    """根据支持的频率判断计划类型"""
    if '1m' in frequencies:
        return "Professional/Enterprise Plan"
    elif '10m' in frequencies:
        return "Advanced Plan"
    elif '1h' in frequencies:
        return "Free/Starter Plan"
    else:
        return "Unknown Plan"


# API_KEY = '1zWq4Li0KlvJgokm8mJoXa8OeB2'  # dixinsuanlieth1@163.com\
# API_KEY = '1zV4A93k4g2KGDPRT2GJJ5XL5l9'    # jeffzhangzhenda@hotmail.com
API_KEY = '1zWq4Li0KlvJgokm8mJoXa8OeB2'
# check_api_plan(API_KEY)
get_data_frequencies(API_KEY)